This is a course diary for the UH course Introduction to Open Data Science. I was introduced to this course by our PhD-program’s advisor and it will be included as a course in my transferrable studies quota (10 credits).
The link for this diary is: https://villetan.github.io/IODS-project/
# This is a so-called "R chunk" where you can write R code.
date()
## [1] "Fri Dec 3 15:28:54 2021"
Describe the work you have done this week and summarize your learning.
setwd("~/Koulu/IODS-project")
date()
## [1] "Fri Dec 3 15:28:54 2021"
Lets read the data in from local file…
data = read.csv("data/wk2data.csv")
… and see the summary of it.
summary(data)
## gender Age Attitude Points
## Length:166 Min. :17.00 Min. :14.00 Min. : 7.00
## Class :character 1st Qu.:21.00 1st Qu.:26.00 1st Qu.:19.00
## Mode :character Median :22.00 Median :32.00 Median :23.00
## Mean :25.51 Mean :31.43 Mean :22.72
## 3rd Qu.:27.00 3rd Qu.:37.00 3rd Qu.:27.75
## Max. :55.00 Max. :50.00 Max. :33.00
## deep stra surf
## Min. :1.583 Min. :1.250 Min. :1.583
## 1st Qu.:3.333 1st Qu.:2.625 1st Qu.:2.417
## Median :3.667 Median :3.188 Median :2.833
## Mean :3.680 Mean :3.121 Mean :2.787
## 3rd Qu.:4.083 3rd Qu.:3.625 3rd Qu.:3.167
## Max. :4.917 Max. :5.000 Max. :4.333
Let’s also plot a graphical summary.
library(GGally)
## Loading required package: ggplot2
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
library(ggplot2)
p <- ggpairs(data, mapping = aes(), lower = list(combo = wrap("facethist", bins = 20)))
p
First, lets look at the distributions of the variables individually. There are more females present in the data set. The ages of the subjects are right skewed, so that people in their 20’s are more prevalent. Points have a small spike in presence of low points, but other than that it is near Gaussian in the region above 15 points. Other variables seem to be balanced rather well over their domain.
To name few interesting or meaningful pairwise relationships, the correlation between deep and surf variables is the highest. Without knowing too much about them, they sound likethey should indeed have negative correlation: High deep approach to the course, would mean low surface approach to the course. Another clear correlation is between Attitude and Points: good attitude correlates with good score from the course. We should be careful of commenting on causal relationship, but for the layman this would suggest that good attitudes yield good scores.
Next, lets fit a regression model with three variables and print the summary.
lm_fit = lm("Points ~ Attitude + deep + stra", data = data)
summary(lm_fit)
##
## Call:
## lm(formula = "Points ~ Attitude + deep + stra", data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -17.5239 -3.4276 0.5474 3.8220 11.5112
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.39145 3.40775 3.343 0.00103 **
## Attitude 0.35254 0.05683 6.203 4.44e-09 ***
## deep -0.74920 0.75066 -0.998 0.31974
## stra 0.96208 0.53668 1.793 0.07489 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.289 on 162 degrees of freedom
## Multiple R-squared: 0.2097, Adjusted R-squared: 0.195
## F-statistic: 14.33 on 3 and 162 DF, p-value: 2.521e-08
It seems that the attitude is the only statistically significant feature explaining good (or bad) points in the course. What this means in laymen terms is that the coefficients for the deep and stra might as well have been 0 and thus they would have not contributed to the score itself.
Lets remove stra and deep since they are non-significant, we’ll also keep the Intercept therm as it showed significance as well.
lm_fit_ = lm("Points ~ Attitude", data = data)
summary(lm_fit_)
##
## Call:
## lm(formula = "Points ~ Attitude", data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -16.9763 -3.2119 0.4339 4.1534 10.6645
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.63715 1.83035 6.358 1.95e-09 ***
## Attitude 0.35255 0.05674 6.214 4.12e-09 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared: 0.1906, Adjusted R-squared: 0.1856
## F-statistic: 38.61 on 1 and 164 DF, p-value: 4.119e-09
Now, they both are significant with p-values effectively zero. This means that we can be pretty certain that the coefficient estimates are not zeros.
The relationship between Attitude and Points is clear positive trend as seen on the plot below. There the regression line found is plotted with black solid line.
plot(data$Attitude, data$Points, xlab = "Attitide", ylab="Points")
abline(a=lm_fit_$coefficients["(Intercept)"], b=lm_fit_$coefficients["Attitude"])
The multiple R-squared is the proportion of variance explained by the linear model. So the linear model explains about 20% of the variance in the response variable, that is, points. The rest of the 80% of the variance seem to be inherent to the data.
Lets plot Residuals vs. fitted values, normal QQ-plot and residual vs. leverage.
par(mfrow=c(2,2))
plot(lm_fit_, which = c(1,2,5))
The interpretation of “Residuals vs. fitted” is that one can see where the linear model makes mistakes. For example if there is non-linearity, then it is expected to be visible in this plot. The closer to the zero line the residuals are, the better the model. A perfect model would have a straight line at 0. In our model there is no pattern of nonlinearity as the points are uniformly distributed across different locations of x-axis.
The second plot, the QQ-plot, estimates if the errors of the model are really normally distributed, which is an assumption of the linear model. Since the QQ-plot is not completely straight, there are slight evidence, that the residuals are not Normal, but rather left skewed. See the plot below. However, the skew is very minor.
The third plot, Residuals vs. leverage, studies if a single (or a group) data point is responsible for the “fit” more than the others. It seems that no single data point is affecting the fit significantly more than others.
hist(lm_fit_$residuals, main="Residuals")
Lets read the data we generated using create_alc.R script and see that it looks ok.
alc_data = read.csv("data/alc_data.csv")
print(dim(alc_data))
## [1] 370 35
str(alc_data)
## 'data.frame': 370 obs. of 35 variables:
## $ school : chr "GP" "GP" "GP" "GP" ...
## $ sex : chr "F" "F" "F" "F" ...
## $ age : int 15 15 15 15 15 15 15 15 15 15 ...
## $ address : chr "R" "R" "R" "R" ...
## $ famsize : chr "GT3" "GT3" "GT3" "GT3" ...
## $ Pstatus : chr "T" "T" "T" "T" ...
## $ Medu : int 1 1 2 2 3 3 3 2 3 3 ...
## $ Fedu : int 1 1 2 4 3 4 4 2 1 3 ...
## $ Mjob : chr "at_home" "other" "at_home" "services" ...
## $ Fjob : chr "other" "other" "other" "health" ...
## $ reason : chr "home" "reputation" "reputation" "course" ...
## $ guardian : chr "mother" "mother" "mother" "mother" ...
## $ traveltime: int 2 1 1 1 2 1 2 2 2 1 ...
## $ studytime : int 4 2 1 3 3 3 3 2 4 4 ...
## $ schoolsup : chr "yes" "yes" "yes" "yes" ...
## $ famsup : chr "yes" "yes" "yes" "yes" ...
## $ activities: chr "yes" "no" "yes" "yes" ...
## $ nursery : chr "yes" "no" "yes" "yes" ...
## $ higher : chr "yes" "yes" "yes" "yes" ...
## $ internet : chr "yes" "yes" "no" "yes" ...
## $ romantic : chr "no" "yes" "no" "no" ...
## $ famrel : int 3 3 4 4 4 4 4 4 4 4 ...
## $ freetime : int 1 3 3 3 2 3 2 1 4 3 ...
## $ goout : int 2 4 1 2 1 2 2 3 2 3 ...
## $ Dalc : int 1 2 1 1 2 1 2 1 2 1 ...
## $ Walc : int 1 4 1 1 3 1 2 3 3 1 ...
## $ health : int 1 5 2 5 3 5 5 4 3 4 ...
## $ alc_use : num 1 3 1 1 2.5 1 2 2 2.5 1 ...
## $ high_use : logi FALSE TRUE FALSE FALSE TRUE FALSE ...
## $ failures : int 0 1 0 0 1 0 1 0 0 0 ...
## $ paid : chr "yes" "no" "no" "no" ...
## $ absences : int 3 2 8 2 5 2 0 1 9 10 ...
## $ G1 : int 10 10 14 10 12 12 11 10 16 10 ...
## $ G2 : int 12 8 13 10 12 12 6 10 16 10 ...
## $ G3 : int 12 8 12 9 12 12 6 10 16 10 ...
Let us select 4 interesting variables to seek the relationship with the alcohol consumption.
interesting_cols = c("freetime", "romantic", "address", "famrel")
The hypothesis is that these variables correlate with alieness to the society, which in turn, I speculate, affects the alcohol consumption. I speculate that freetime and ruralness correlate with alcohol consumption positively, while being in a romantic relationship and having good family relations correlate negatively.
library(ggplot2)
library(GGally)
cor_data = alc_data[, c("alc_use", interesting_cols)]
#cast as factors so that they are visualised correctly
cor_data$freetime = as.factor(cor_data$freetime)
cor_data$romantic = as.factor(cor_data$romantic)
cor_data$address = as.factor(cor_data$address)
cor_data$famrel = as.factor(cor_data$famrel)
ggpairs(cor_data)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
I have non-significant support for the hypotheses made above for all but “romantic” relationship. So it seems that relationship status has absolutely no correlation with the alcohol consumption.
Lets study the problem with logistic regression model.
cor_data$freetime = as.numeric(cor_data$freetime)
cor_data$famrel = as.numeric(cor_data$famrel)
glm_data = cbind("high_use"=alc_data$high_use, cor_data[,interesting_cols])
logreg_fit = glm(high_use ~ ., data = glm_data, family="binomial")
For the continuous (ordinal features, that is, freetime and famrel) we can exponentiate, to get the odds ratios:
exp(logreg_fit$coefficients[c("freetime", "famrel")])
## freetime famrel
## 1.5537064 0.6932053
So free time, being having a unit more of free time, increases the chances of high use of alcohol 1.5 times higher. On the other hand, having a unit increase in family relations, that is having better family relationships, makes decreases the chances of high use of alcohol by 1.45 times (because 0.69, which is 1 / 1.45).
The same happens with the discrete features, but we need to be careful with the interpretation of unit addition.
exp(logreg_fit$coefficients[c("romanticyes", "addressU")])
## romanticyes addressU
## 0.7760629 0.5883402
Here it seems that romantic relation and address in urban area seem to have negative effect on the high use of alcohol, just like predicted.
The confidence intervals can be fetched with the following command
exp(confint(logreg_fit))
## Waiting for profiling to be done...
## 2.5 % 97.5 %
## (Intercept) 0.1940075 2.3182620
## freetime 1.2228777 1.9926747
## romanticyes 0.4657483 1.2726638
## addressU 0.3451026 1.0102441
## famrel 0.5378060 0.8906739
So, the only confidence intervals not covering the “no effect” value of 1 are freetime and famrel, meaning that they provide more statistical evidence that indeed more freetime is associated with higher use and better family relationships are related with not high use.
Lets create the 2x2 cross-tabulation, also known as confusion matrix,
cmat = table(high_use = glm_data$high_use, prediction = (predict(logreg_fit, newdata=glm_data, type="response") > 0.5))
print(cmat)
## prediction
## high_use FALSE TRUE
## FALSE 248 11
## TRUE 104 7
and compute the training error:
#training error:
sum(c(cmat[1,2], cmat[2,1])) / sum(cmat)
## [1] 0.3108108
#random guessing:
print(mean(glm_data$high_use))
## [1] 0.3
The model misclassifices 31% of the training cases. So the interpretation is that on average 3 out of 10 samples is misclassified. With random guessing one gets, on average, as low errors as predicting the majority class. That is, the random guessing is actually better, because it gets an error as low as 30%. So this means that the model fit to the data is actually very poor, and the interpretation should not be trusted.
Let us look at the Boston dataset from MASS package
library(MASS)
data = Boston
str(data)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
Boston dataset is about housing values in suburbs of Boston. It includes 14 features defining variables that might or might not be relevant for the median value of the houses in that area. The features are:
Lets grpahically look at the data and summarize the data
library(ggplot2)
library(GGally)
#lets cast the integers to factors
data$chas = as.factor(data$chas)
ggpairs(data = data, aes(colour = chas, alpha = 0.4))
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
There are some interesting findings in the graphical overview. Firstly the distribution between chas variable is really unbalanced, which is expected as there can only be so many houses near the river and more further away. Some nonlinear clear relationships are present for example between medv-lstat and nox-dis. Also number of rooms have the anticipated positive correlation with the median value of the house.
Lets print the summary
summary(data)
## crim zn indus chas nox
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 0:471 Min. :0.3850
## 1st Qu.: 0.08205 1st Qu.: 0.00 1st Qu.: 5.19 1: 35 1st Qu.:0.4490
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.5380
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.5547
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.6240
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :0.8710
## rm age dis rad
## Min. :3.561 Min. : 2.90 Min. : 1.130 Min. : 1.000
## 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100 1st Qu.: 4.000
## Median :6.208 Median : 77.50 Median : 3.207 Median : 5.000
## Mean :6.285 Mean : 68.57 Mean : 3.795 Mean : 9.549
## 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188 3rd Qu.:24.000
## Max. :8.780 Max. :100.00 Max. :12.127 Max. :24.000
## tax ptratio black lstat
## Min. :187.0 Min. :12.60 Min. : 0.32 Min. : 1.73
## 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38 1st Qu.: 6.95
## Median :330.0 Median :19.05 Median :391.44 Median :11.36
## Mean :408.2 Mean :18.46 Mean :356.67 Mean :12.65
## 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23 3rd Qu.:16.95
## Max. :711.0 Max. :22.00 Max. :396.90 Max. :37.97
## medv
## Min. : 5.00
## 1st Qu.:17.02
## Median :21.20
## Mean :22.53
## 3rd Qu.:25.00
## Max. :50.00
Unlike the datacamp says, there is a factor variable in the data, lets not normalize that. Lets normalize the others (although I am not sure if it should be done for proportions)
sdata = scale(data[,colnames(data) != "chas"])
sdata = as.data.frame(sdata)
sdata[,"chas"] = data$chas
summary(sdata)
## crim zn indus nox
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563 Min. :-1.4644
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668 1st Qu.:-0.9121
## Median :-0.390280 Median :-0.48724 Median :-0.2109 Median :-0.1441
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150 3rd Qu.: 0.5981
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202 Max. : 2.7296
## rm age dis rad
## Min. :-3.8764 Min. :-2.3331 Min. :-1.2658 Min. :-0.9819
## 1st Qu.:-0.5681 1st Qu.:-0.8366 1st Qu.:-0.8049 1st Qu.:-0.6373
## Median :-0.1084 Median : 0.3171 Median :-0.2790 Median :-0.5225
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4823 3rd Qu.: 0.9059 3rd Qu.: 0.6617 3rd Qu.: 1.6596
## Max. : 3.5515 Max. : 1.1164 Max. : 3.9566 Max. : 1.6596
## tax ptratio black lstat
## Min. :-1.3127 Min. :-2.7047 Min. :-3.9033 Min. :-1.5296
## 1st Qu.:-0.7668 1st Qu.:-0.4876 1st Qu.: 0.2049 1st Qu.:-0.7986
## Median :-0.4642 Median : 0.2746 Median : 0.3808 Median :-0.1811
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 1.5294 3rd Qu.: 0.8058 3rd Qu.: 0.4332 3rd Qu.: 0.6024
## Max. : 1.7964 Max. : 1.6372 Max. : 0.4406 Max. : 3.5453
## medv chas
## Min. :-1.9063 0:471
## 1st Qu.:-0.5989 1: 35
## Median :-0.1449
## Mean : 0.0000
## 3rd Qu.: 0.2683
## Max. : 2.9865
We can see that the means are all 0 and the sds are ones as well (below).
apply(sdata, 2, sd)
## crim zn indus nox rm age dis rad
## 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000
## tax ptratio black lstat medv chas
## 1.000000 1.000000 1.000000 1.000000 1.000000 0.253994
#also save kmeand dataset that is scaled
kdata = sdata
Lets create a categorical variable out of crime rate
bins <- quantile(sdata$crim)
crime <- cut(sdata$crim, breaks = bins, include.lowest = TRUE)
#replace the earlier crime feature with the binned one
sdata$crim = crime
Lets shuffle the data set and split it into training and testing
N_train = floor(0.8 * nrow(sdata))
train_inds = sample(nrow(sdata), N_train)
train = sdata[train_inds,]
test = sdata[-train_inds, ]
Lets fit the LDA to the data using crim (binned) as the target variable
lda.fit <- lda(crim ~ ., data = train)
# print the lda.fit object
lda.fit
## Call:
## lda(crim ~ ., data = train)
##
## Prior probabilities of groups:
## [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
## 0.2549505 0.2500000 0.2524752 0.2425743
##
## Group means:
## zn indus nox rm age
## [-0.419,-0.411] 0.95726140 -0.9262993 -0.8873344 0.4046820 -0.8719299
## (-0.411,-0.39] -0.06823292 -0.2707257 -0.5572880 -0.1430870 -0.3071594
## (-0.39,0.00739] -0.38551208 0.2037547 0.4042552 0.1513709 0.4367049
## (0.00739,9.92] -0.48724019 1.0149946 1.0360929 -0.4032615 0.8277638
## dis rad tax ptratio black
## [-0.419,-0.411] 0.9301657 -0.6819317 -0.7353067 -0.42208269 0.37841161
## (-0.411,-0.39] 0.3249725 -0.5440892 -0.4812497 -0.08373244 0.31146523
## (-0.39,0.00739] -0.3927093 -0.3884966 -0.2837095 -0.28241632 0.06642329
## (0.00739,9.92] -0.8646270 1.6596029 1.5294129 0.80577843 -0.81887668
## lstat medv chas1
## [-0.419,-0.411] -0.76096967 0.4636547563 0.03883495
## (-0.411,-0.39] -0.12307762 0.0007391062 0.07920792
## (-0.39,0.00739] -0.03804626 0.1999283998 0.13725490
## (0.00739,9.92] 0.84559801 -0.6489565143 0.07142857
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.12684587 0.625529550 -0.85047657
## indus -0.01291686 -0.251568977 0.38566425
## nox 0.28366574 -0.825536531 -1.41540222
## rm -0.10785638 -0.082268486 -0.20314781
## age 0.37506741 -0.286588303 -0.13540504
## dis -0.10306102 -0.219520687 0.03477983
## rad 3.21057979 0.973441239 0.03939917
## tax 0.01147160 -0.003211558 0.33684357
## ptratio 0.15313340 -0.009195934 -0.30949471
## black -0.16503710 0.009372087 0.12172554
## lstat 0.14149124 -0.212440165 0.49025938
## medv 0.17015110 -0.408595498 -0.10020284
## chas1 -0.19425046 -0.128469326 0.40985910
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9488 0.0394 0.0118
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crime)
# plot the lda results
plot(lda.fit, dimen = 2)
lda.arrows(lda.fit, myscale = 1)
Lets then save the crime categories for the test set and remove them from test set to avoid information leakage.
test_resp = test$crim
test$crim = NULL
And then predict the values for the test set and plot the confusion matrix
test_preds = predict(lda.fit, newdata = test)
table(correct = test_resp, preds = test_preds$class)
## preds
## correct [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
## [-0.419,-0.411] 16 7 1 0
## (-0.411,-0.39] 5 14 6 0
## (-0.39,0.00739] 1 8 15 0
## (0.00739,9.92] 0 0 1 28
The corss tabulation shows good pattern of highest values on the diagonal (meaning correct class) and least amount far away in the quantiles. In the middle classes there are some confusion with the nearby classes, which is better than misclassifying them “hardly”. Notice, however, that not every classification task possess this quantity of the classes being “close” to one another.
Lets then move on to the clustering part of the analysis, we use kdata as it is already a scaled data set and it was saved earlier. Lets begin by calculating the distances
summary(dist(kdata))
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.1343 3.2663 4.6116 4.7275 5.9572 13.8843
summary(dist(kdata, method = "manhattan"))
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.2662 8.1777 12.2363 13.1698 17.1841 45.9247
Now we can cluster the data and plot the pairs with clusters as the colors. Lets define a function so it is easy to experiment with different number of clusters (and start by clustering to 4)
fit_and_plot_cluster = function(n_clusters){
colors = c("red", "blue", "purple", "black", "orange")#max number of clusters is 5
kfit = kmeans(kdata, centers = n_clusters)
color_vec = kfit$cluster
for(ii in 1:n_clusters){
color_vec[color_vec == ii] = colors[ii]
}
pairs(kdata, col = color_vec)
return(kfit)
}
fit_and_plot_cluster(4)
## K-means clustering with 4 clusters of sizes 97, 56, 154, 199
##
## Cluster means:
## crim zn indus nox rm age
## 1 -0.4120558 1.6745189 -1.0359503 -1.1182625 0.5305857 -1.35815693
## 2 -0.3470984 -0.1679587 -0.7379608 -0.2054542 1.5550146 0.14445239
## 3 0.8722607 -0.4872402 1.0959794 1.1588553 -0.4882829 0.78422706
## 4 -0.3764886 -0.3918978 -0.1355168 -0.2939036 -0.3183521 0.01447699
## dis rad tax ptratio black lstat
## 1 1.44122577 -0.6183873 -0.6226414 -0.6399378 0.3586836 -0.871808841
## 2 -0.32821546 -0.4281460 -0.7072712 -0.9436882 0.3448332 -0.977374554
## 3 -0.84884210 1.3128255 1.3507941 0.5688270 -0.7064544 0.916774340
## 4 0.04674799 -0.5940472 -0.5428085 0.1372922 0.2748292 -0.009471436
## medv chas
## 1 0.6043115 0.04123711
## 2 1.6897067 0.16071429
## 3 -0.7370701 0.06493506
## 4 -0.1996633 0.06030151
##
## Clustering vector:
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
## 2 4 2 2 2 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
## 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
## 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 1
## 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
## 1 1 1 1 4 4 4 4 4 4 1 1 1 1 1 1 1 1 1 4
## 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
## 4 4 1 1 1 1 1 1 4 4 4 4 4 4 4 4 4 4 4 4
## 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
## 1 4 1 1 4 4 4 4 2 2 4 4 4 4 4 4 4 2 2 2
## 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
## 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
## 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
## 4 4 4 4 4 4 4 4 4 4 4 4 4 4 3 4 4 4 3 4
## 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 2 4 4
## 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
## 4 2 2 2 4 4 2 4 4 4 4 4 4 4 4 2 4 4 2 2
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
## 2 2 2 2 4 4 2 1 1 1 1 1 1 1 1 1 1 1 1 1
## 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
## 1 1 1 1 1 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
## 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
## 2 4 2 2 2 2 2 2 2 2 4 2 2 2 2 4 4 2 1 1
## 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
## 1 1 1 1 4 4 1 4 1 1 1 1 1 1 1 1 1 2 2 2
## 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
## 2 2 2 2 2 4 2 2 2 4 4 1 4 2 1 1 1 1 1 2
## 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
## 2 1 2 1 1 1 1 1 1 1 1 1 1 4 4 1 4 4 1 1
## 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
## 1 1 1 1 2 1 2 2 4 4 4 4 4 4 4 4 4 4 4 4
## 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
## 4 4 4 4 4 4 4 4 4 1 4 1 1 4 4 4 4 4 4 4
## 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
## 4 1 4 1 1 4 4 1 1 1 1 1 1 1 1 1 3 3 3 3
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
## 3 3 3 3 3 3 3 3 3 2 2 3 3 3 3 3 3 3 3 3
## 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
## 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4
## 501 502 503 504 505 506
## 4 4 4 4 4 4
##
## Within cluster sum of squares by cluster:
## [1] 454.5407 287.4014 1438.5858 836.9116
## (between_SS / total_SS = 54.3 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
Cluster separation seems to be decent, so that in every plot the different colors somewhat focus on different regions of the plot. However there are still some overlaps, so lets try to find the optimal number of clusters
set.seed(42)
k_max = 15
twcss <- sapply(1:k_max, function(k){kmeans(kdata, k)$tot.withinss})
qplot(x = 1:k_max, y = twcss, geom = 'line')
So it seems that the most radical drop is at 5 clusters, so lets go with that
fit_and_plot_cluster(5)
## K-means clustering with 5 clusters of sizes 130, 107, 154, 65, 50
##
## Cluster means:
## crim zn indus nox rm age dis
## 1 1.0751732 -0.4872402 1.0149946 1.0214115 -0.3916946 0.7502046 -0.8176637
## 2 -0.3231486 -0.4822312 0.6308150 0.5041272 -0.5223445 0.7753457 -0.5711540
## 3 -0.3976664 -0.1658009 -0.5908351 -0.6609769 -0.1605287 -0.6491081 0.5401341
## 4 -0.4140702 2.2813035 -1.1562550 -1.1768217 0.7293996 -1.4086475 1.5645584
## 5 -0.3408088 -0.1562287 -0.6660268 -0.1688251 1.6824321 0.2207229 -0.3493438
## rad tax ptratio black lstat medv
## 1 1.6596029 1.5294129 0.8057784 -0.76735584 0.8657319 -0.72260607
## 2 -0.5943978 -0.1915536 0.0874508 0.03673407 0.5492158 -0.48624639
## 3 -0.5739417 -0.6919945 -0.0640434 0.36078750 -0.3846437 0.01486057
## 4 -0.6656011 -0.5702843 -0.8094692 0.35416061 -0.9741045 0.81491803
## 5 -0.4099346 -0.6938362 -1.0326050 0.34487995 -0.9751860 1.81417906
## chas
## 1 0.04615385
## 2 0.10280374
## 3 0.03896104
## 4 0.06153846
## 5 0.16000000
##
## Clustering vector:
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
## 3 3 5 3 5 3 3 3 2 3 3 3 3 3 3 3 3 2 3 3
## 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
## 2 2 2 2 2 2 2 2 2 3 2 2 2 2 2 3 3 3 3 4
## 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
## 4 3 3 3 3 3 3 3 2 3 3 3 3 3 4 4 4 4 3 3
## 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
## 3 3 3 3 4 4 4 3 3 3 3 3 3 3 3 3 3 3 3 3
## 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
## 3 3 3 3 3 3 3 3 3 5 3 3 3 3 3 3 3 5 5 5
## 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
## 3 3 2 2 2 2 2 2 2 2 3 2 2 2 2 2 2 2 2 2
## 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 5 2 2
## 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
## 2 5 5 5 2 2 5 2 2 2 2 2 3 3 3 3 3 3 5 5
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
## 5 3 5 5 3 3 5 4 4 4 4 4 4 4 4 4 4 4 4 4
## 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
## 4 4 4 4 4 3 3 3 3 2 2 2 3 3 3 3 3 5 2 2
## 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
## 5 2 5 5 5 5 5 5 5 3 3 5 5 5 3 3 3 5 4 3
## 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
## 3 3 3 4 3 3 3 3 3 3 3 3 4 4 4 4 4 5 5 5
## 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
## 5 5 5 5 5 3 5 5 5 3 3 3 3 5 4 4 4 4 3 5
## 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
## 5 5 5 4 4 4 4 4 4 4 4 4 4 3 3 3 3 3 4 4
## 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
## 4 3 4 4 5 3 5 3 3 3 3 3 2 3 3 2 2 2 3 3
## 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
## 3 4 3 4 4 3 3 4 4 4 4 4 4 4 4 4 1 1 1 1
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
## 1 1 1 1 1 1 1 1 1 5 5 1 1 1 1 1 1 1 1 1
## 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
## 1 1 1 1 1 1 1 1 2 2 2 2 2 2 3 3 2 2 2 2
## 501 502 503 504 505 506
## 2 2 2 2 2 2
##
## Within cluster sum of squares by cluster:
## [1] 1044.1446 620.4854 463.8670 288.6658 255.5570
## (between_SS / total_SS = 59.5 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
Some of the variables are very well separated in the clusters, i.e., nox vs age/dis/rad, where e.g. the purple cluster is such that the nox, rad and age are high and dis is low. Similar differences can be recognized in other clusters as well.
Lets read the csv from the file, as there might be a mistake in the data preparation.
data = read.csv("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human2.txt")
dim(data)
## [1] 155 8
Lets plot the data
library(GGally)
library(ggplot2)
ggpairs(data)
Some of the distributions are really skewed towards the low values. Like GNI and Mat.Mor and Ado.Birth. Life.Exp is skewed towards the right side, meaning that most of the countries have decently high life expetation. There are also some clear trends in the data like Life.Exp and Mat.Mor, which is logical: lower life expectancy also correlates with mother mortality.
Lets then move on to computing the PCA. First on non-standardized data set.
pcafit = prcomp(data)
biplot(pcafit)
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
The plot shows that GNI has vastly greater magnitude than other variables.
Lets then normalize the data and repeat
data_norm = scale(data)
pcafit = prcomp(data_norm)
biplot(pcafit)
The results are different, and the reason for this is that the PCA finds the axis of maximal variance in the data. If the scale of one variable is large, then of course the variance will be large as well, and thus that direction has the maximal variance. When the data set is normalized, then there is no discrepancy between the scales of the variables, and the PCA finds actually meaningful directions of principal component. The names describe the values of countries in PC1 and PC2 and the red texts desribe the values of the principal component coefficients along corresponding PC (PC1 and PC2). For example the coefficient for Edu.Exp is approx. 0.12 for PC1 and 0.04 for PC2. It means that for example Netherlands have high value for Edu.Exp. Another example is in Rwanda Labo.FM is high, and in Jordan and Yemen this is low. However both of these are similar in the Edu.Exp, Life.exp and Mat.mor axis.
In the countries most of the variation is from the Edu.exp, Edu.Pm, GNI, Life.exp vs. Mat.mor and Ado.Birth. Then the second highest variation (second component) combines the Parli.F and Labo.FM.
Then next we look at the tea data set.
#install.packages("FactoMineR")
library(FactoMineR)
data(tea)
dim(tea)
## [1] 300 36
str(tea)
## 'data.frame': 300 obs. of 36 variables:
## $ breakfast : Factor w/ 2 levels "breakfast","Not.breakfast": 1 1 2 2 1 2 1 2 1 1 ...
## $ tea.time : Factor w/ 2 levels "Not.tea time",..: 1 1 2 1 1 1 2 2 2 1 ...
## $ evening : Factor w/ 2 levels "evening","Not.evening": 2 2 1 2 1 2 2 1 2 1 ...
## $ lunch : Factor w/ 2 levels "lunch","Not.lunch": 2 2 2 2 2 2 2 2 2 2 ...
## $ dinner : Factor w/ 2 levels "dinner","Not.dinner": 2 2 1 1 2 1 2 2 2 2 ...
## $ always : Factor w/ 2 levels "always","Not.always": 2 2 2 2 1 2 2 2 2 2 ...
## $ home : Factor w/ 2 levels "home","Not.home": 1 1 1 1 1 1 1 1 1 1 ...
## $ work : Factor w/ 2 levels "Not.work","work": 1 1 2 1 1 1 1 1 1 1 ...
## $ tearoom : Factor w/ 2 levels "Not.tearoom",..: 1 1 1 1 1 1 1 1 1 2 ...
## $ friends : Factor w/ 2 levels "friends","Not.friends": 2 2 1 2 2 2 1 2 2 2 ...
## $ resto : Factor w/ 2 levels "Not.resto","resto": 1 1 2 1 1 1 1 1 1 1 ...
## $ pub : Factor w/ 2 levels "Not.pub","pub": 1 1 1 1 1 1 1 1 1 1 ...
## $ Tea : Factor w/ 3 levels "black","Earl Grey",..: 1 1 2 2 2 2 2 1 2 1 ...
## $ How : Factor w/ 4 levels "alone","lemon",..: 1 3 1 1 1 1 1 3 3 1 ...
## $ sugar : Factor w/ 2 levels "No.sugar","sugar": 2 1 1 2 1 1 1 1 1 1 ...
## $ how : Factor w/ 3 levels "tea bag","tea bag+unpackaged",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ where : Factor w/ 3 levels "chain store",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ price : Factor w/ 6 levels "p_branded","p_cheap",..: 4 6 6 6 6 3 6 6 5 5 ...
## $ age : int 39 45 47 23 48 21 37 36 40 37 ...
## $ sex : Factor w/ 2 levels "F","M": 2 1 1 2 2 2 2 1 2 2 ...
## $ SPC : Factor w/ 7 levels "employee","middle",..: 2 2 4 6 1 6 5 2 5 5 ...
## $ Sport : Factor w/ 2 levels "Not.sportsman",..: 2 2 2 1 2 2 2 2 2 1 ...
## $ age_Q : Factor w/ 5 levels "15-24","25-34",..: 3 4 4 1 4 1 3 3 3 3 ...
## $ frequency : Factor w/ 4 levels "1/day","1 to 2/week",..: 1 1 3 1 3 1 4 2 3 3 ...
## $ escape.exoticism: Factor w/ 2 levels "escape-exoticism",..: 2 1 2 1 1 2 2 2 2 2 ...
## $ spirituality : Factor w/ 2 levels "Not.spirituality",..: 1 1 1 2 2 1 1 1 1 1 ...
## $ healthy : Factor w/ 2 levels "healthy","Not.healthy": 1 1 1 1 2 1 1 1 2 1 ...
## $ diuretic : Factor w/ 2 levels "diuretic","Not.diuretic": 2 1 1 2 1 2 2 2 2 1 ...
## $ friendliness : Factor w/ 2 levels "friendliness",..: 2 2 1 2 1 2 2 1 2 1 ...
## $ iron.absorption : Factor w/ 2 levels "iron absorption",..: 2 2 2 2 2 2 2 2 2 2 ...
## $ feminine : Factor w/ 2 levels "feminine","Not.feminine": 2 2 2 2 2 2 2 1 2 2 ...
## $ sophisticated : Factor w/ 2 levels "Not.sophisticated",..: 1 1 1 2 1 1 1 2 2 1 ...
## $ slimming : Factor w/ 2 levels "No.slimming",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ exciting : Factor w/ 2 levels "exciting","No.exciting": 2 1 2 2 2 2 2 2 2 2 ...
## $ relaxing : Factor w/ 2 levels "No.relaxing",..: 1 1 2 2 2 2 2 2 2 2 ...
## $ effect.on.health: Factor w/ 2 levels "effect on health",..: 2 2 2 2 2 2 2 2 2 2 ...
library(dplyr)
##
## Attaching package: 'dplyr'
## The following object is masked from 'package:MASS':
##
## select
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(tidyr)
keep_columns <- c("Tea", "How", "how", "sugar", "where", "lunch")
tea_time <- select(tea, keep_columns)
## Note: Using an external vector in selections is ambiguous.
## ℹ Use `all_of(keep_columns)` instead of `keep_columns` to silence this message.
## ℹ See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>.
## This message is displayed once per session.
gather(tea_time) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8))
## Warning: attributes are not identical across measure variables;
## they will be dropped
Then time for MCA.
mcafit = MCA(tea_time, graph=FALSE)
plot(mcafit)
MCA is the PCA equivalent for factored data. Because it is not really meaningful to calculate variance of a factor (at least in the standard way, we need to do some special treatment, that is, MCA). It means that most of the variation in the data set comes from the unpacked and tea shop dimensions of the where and how features. Similarly for other variables and the second dimension the other and green of Tea and How explain the other second dimension’s variability.
(more chapters to be added similarly as we proceed with the course!)